package fr.ensisa.sunspot;

import fr.ensisa.sunspot.actor.osc.TcpServer;
import fr.ensisa.sunspot.profile.ProfileFactory;

public class Application implements IKernel,Runnable {

    private ProfileFactory profile;
    private ActorManager manager;
    private long timeStamp;
    
	@Override
	public ActorManager getActorManager() {
		return manager;
	}

	@Override
	public ProfileFactory getProfileFactory() {
		return profile;
	}

	@Override
	public long getTimeStamp() {
		return timeStamp;
	}

	@Override
	public void run() {
        Logger.setDebugSilent(true);
        Logger.setInfoSilent(true);
        profile = new ProfileFactory (this);
        manager = new ActorManager (this);
        
		//manager.addAllActors(profile.desktopProfile());
		//manager.addAllActors(profile.desktopProfile());
		manager.addAllActors(profile.automateTest());
        
        long startTime = System.currentTimeMillis();
//        int timeSample = profile.getTimeSample();
        int timeSample = 100;
        try {
            boolean loop = true;
            while (loop) {
                timeStamp = System.currentTimeMillis()-startTime;
                Logger.getLogger().infoln ("MainLoop", "timeStamp ", timeStamp);
                long before = System.currentTimeMillis();
                manager.process(timeStamp);
                long after = System.currentTimeMillis();
                Logger.getLogger().infoln ("MainLoop", "elapsed ", after-before);
                long time = timeSample - (System.currentTimeMillis()-startTime-timeStamp);
                if (time > 0) Thread.sleep(time);
                else {
                    System.err.println ("MainLoop @time"+timeStamp+" timeshift "+(after-before)+"/"+timeSample);
                    Thread.yield();
                }
            }
        }
        catch (InterruptedException ex) {
        	ex.printStackTrace();
        }
		
	}
	
	public static void main(String[] args) {
		Application application = new Application();
		Thread thread = new Thread(application);
		thread.start();
	}

}
